﻿using System;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using Kobets.Automation.Chimera.Orchestrator.Shared;
using Kobets.Automation.Chimera.Orchestrator.Models;

namespace Kobets.Automation.Chimera.Orchestrator.Controllers
{
    [LogActionFilter]
    public class ResourceController : Controller
    {
        public ActionResult Index(string error)
        {
            ViewBag.Title = "Resources";
            return View("Index");
        }

        public ActionResult GetData([DataSourceRequest]DataSourceRequest request)
        {
            var data = Shared.Common.GetAgentsList();
            var gridOutput = data.Select(agent => new AgentsModel { Name = agent.Name, Grp = agent.Group, Attributes = (agent.Attributes == null) ? "" : Common.CommonMethods.AttributesToText(agent.Attributes) }).ToList();

            return Json(gridOutput.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditData([DataSourceRequest]DataSourceRequest request, AgentsModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                Shared.Common.SetAgentGroup(model.Name, model.Grp);
                
                if (!String.IsNullOrWhiteSpace(model.Attributes))
                    Shared.Common.SetAttributes(model.Name, Common.CommonMethods.TextToAttributes(model.Attributes));
            }

            return Json(ModelState.ToDataSourceResult());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddData([DataSourceRequest]DataSourceRequest request, AgentsModel model)
        {
            if (model != null && ModelState.IsValid)
                if (!String.IsNullOrWhiteSpace(model.Name) && Common.CommonMethods.IsHostAlive(model.Name))
                    Shared.Common.AddAgent(model.Name, model.Grp, Common.CommonMethods.TextToAttributes(model.Attributes));

            return Json(new [] { model }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteData([DataSourceRequest]DataSourceRequest request, AgentsModel model)
        {
            if (model != null)
                Shared.Common.RemoveAgent(model.Name);

            return Json(ModelState.ToDataSourceResult());
        }
    }
}